package com.quick.develop.flowable.framework.core;

import cn.hutool.core.util.StrUtil;
import com.quick.develop.flowable.service.process.IBpmProcessInstanceService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.delegate.event.impl.FlowableEntityEventImpl;
import org.flowable.engine.impl.persistence.entity.HistoricProcessInstanceEntityImpl;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author junyuan.liu
 * @description: TODO 流程历史实例创建 设置相关信息 考虑子流程
 *                  创建的时候还获取不到主流程下传的参数
 *                  子流程不可再设置参数信息 会导致异步JOB执行失败进入 JOB会进入死信表
 *                  暂时停用
 * @date 2022/6/1 15:52
 */
@Component
@Slf4j
public class BpmHiProcessCreatedListener implements FlowableEventListener {
    
    @Resource
    protected IBpmProcessInstanceService bpmProcessInstanceService;
    
    @Resource
    protected RuntimeService runtimeService;
    
    
    @Override
    public void onEvent(FlowableEvent flowableEvent) {
        log.info("===BpmHiProcessCreatedListener===");
        HistoricProcessInstanceEntityImpl entity = (HistoricProcessInstanceEntityImpl) 
                ((FlowableEntityEventImpl) flowableEvent).getEntity();
        String processInstanceId = entity.getProcessInstanceId();
        String superProcessInstanceId = entity.getSuperProcessInstanceId();
        if (isSubProcess(processInstanceId, superProcessInstanceId)) {
            //获取父流程信息
            ProcessInstance supInstance = bpmProcessInstanceService.getProcessInstance(superProcessInstanceId);
            ProcessInstance instance = runtimeService.createProcessInstanceQuery()
                    .processInstanceId(superProcessInstanceId).includeProcessVariables().singleResult();
            Map<String, Object> processVariables = instance.getProcessVariables();
            // runtimeService.setVariable(instance.getProcessInstanceId(), BpmConstants.BUSINESS_KEY, "test-9-21-1");
            // entity.setDescription("112");
            // entity.setBusinessKey("test-9-21-2");
            
        }
    }

    @Override
    public boolean isFailOnException() {
        return true;
    }

    @Override
    public boolean isFireOnTransactionLifecycleEvent() {
        return false;
    }

    @Override
    public String getOnTransaction() {
        return null;
    }
    private Boolean isSubProcess(String processInstanceId, String superProcessInstanceId){
        if (StrUtil.isEmpty(superProcessInstanceId)){
            return false;
        }
        return !processInstanceId.equals(superProcessInstanceId);
    }
}
